package net.zjitc.servlet.file;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "FileUploadServlet",urlPatterns = "/fileUploadServlet")
public class FileUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
     request.setCharacterEncoding("utf-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            for (FileItem item: items) {
                if (item.isFormField()) {
                    String value = item.getString("UTF-8");
                    String fieldName = item.getFieldName();
                    writer.write(fieldName + ":" + value + "<br/>");
                } else {
                    String name = item.getName();
                    String uuid = UUID.randomUUID().toString();
                    uuid = uuid.replace("-", "");
                    String path = this.getServletContext().getRealPath("/uploads");
                    String filename=uuid+"-"+name;
                    File file = new File(path,filename);
                    item.write(file);
                    writer.write("文件已保存");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
